package com.xzsoft.gdwz.schedual;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.xzsoft.gdwz.common.HttpClientUtil;
import com.xzsoft.gdwz.model.UserToken;
import com.xzsoft.gdwz.services.JdOrderService;
import com.xzsoft.gdwz.services.RefreshTokenServices;
import com.xzsoft.gdwz.services.TokenServices;

@Component("refreshTokenServices")
public class RefreshTokenServicesImpl implements RefreshTokenServices {

	Logger logger = Logger.getLogger(RefreshTokenServicesImpl.class);

	@Autowired
	private TokenServices tokenService;

	@Autowired
	private JdOrderService jdOrderService;

	@Scheduled(cron = "0 0 0 * * ?")
	@Override
	public void refreshJdToken() {
		UserToken userToken = getToken("JD");
		String refreshToken = userToken.getRefreshToken();
		String refreshTokenUrl = userToken.getRefreshTokenUrl();
		String clientSecret = userToken.getClientSecret();
		String clientId = userToken.getClientId();
		Map<String, String> map = new HashMap<String, String>();
		map.put("client_id", clientId);
		map.put("client_secret", clientSecret);
		map.put("refresh_token", refreshToken);
		String result = HttpClientUtil.httpPost(refreshTokenUrl, map);
		JSONObject jsonObject = JSONObject.fromObject(result);
		boolean success = (Boolean) jsonObject.get("success");
		if (success) {
			Map resultMap = (Map) jsonObject.get("result");
			resultMap.put("ecommerce_name", "JD");
			tokenService.updateToken(resultMap);
			updateToken("JD");
		} else {
			setJdToken();
		}
	}

	@Override
	public void setJdToken() {
		UserToken userToken = getToken("JD");
		String url = userToken.getGetTokenUrl();
		logger.info(JSONObject.fromObject(userToken).toString());
		String grant_type = userToken.getGrantType();
		String client_id = userToken.getClientId();
		String client_secret = userToken.getClientSecret();
		String timestamp = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
		String password = HttpClientUtil.stringMD5(userToken.getPassword());
		String username = userToken.getUsername();
		Map<String, String> map = new HashMap<String, String>();
		String scope = "";
		String sign = client_secret + timestamp + client_id + username
				+ password + grant_type + scope + client_secret;
		System.out.println("加密前：" + sign);
		sign = HttpClientUtil.stringMD5(sign).toUpperCase();
		System.out.println("加密后：" + sign);
		map.put("grant_type", grant_type);
		map.put("client_id", client_id);
		map.put("client_secret", client_secret);
		map.put("timestamp", timestamp);
		map.put("username", username);
		map.put("password", password);
		map.put("scope", scope);
		map.put("sign", sign);
		System.out.println(JSONObject.fromObject(map).toString());

		String result = HttpClientUtil.httpPost(url, map);
		System.out.println("获取token结果：" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		boolean success = (Boolean) jsonObject.get("success");
		String token = null;
		if (success) {
			Map resultMap = (Map) jsonObject.get("result");
			resultMap.put("ecommerce_name", "JD");
			tokenService.updateToken(resultMap);
		}
	}

	@Override
	@Cacheable(value = "emToken", key = "#ename")
	public UserToken getToken(String ename) {
		UserToken userToken = tokenService.getTokenByName(ename);
		return userToken;
	}

	/**
	 * 获取苏宁token，并存入数据库
	 */
	private void setSNToken() {
		UserToken userToken = getToken("SN");
		String url = userToken.getGetTokenUrl();
		String username = userToken.getUsername();
		String password = userToken.getPassword();
		Map map = new HashMap();
		map.put("appKey", username);
		map.put("appSecret", password);
		map.put("v", "1.0");
		String data = JSONObject.fromObject(map).toString();
		Map dataMap = new HashMap();
		dataMap.put("data", data);
		String result = HttpClientUtil.httpPost(url, dataMap);
		logger.info("获取的token结果为：" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		boolean success = (Boolean) jsonObject.get("isSuccess");
		if (success) {
			Map resultMap = (Map) jsonObject.get("result");
			resultMap.put("ecommerce_name", "SN");
			String accessToken = (String) resultMap.get("accessToken");
			resultMap.put("access_token", accessToken);
			tokenService.updateToken(resultMap);
		}
		updateToken("SN");
	}

	/**
	 * 刷新苏宁token
	 */
	@Override
	// @Scheduled(cron="0 * * * * ?")
	public void refreshSnToken() {
		setSNToken();
	}

	@CachePut(value = "emToken", key = "#ename")
	public UserToken updateToken(String ename) {
		UserToken userToken = tokenService.getTokenByName(ename);
		return userToken;
	}

	

	public static void main(String[] args) {
		RefreshTokenServicesImpl rf = new RefreshTokenServicesImpl();
		rf.setJdToken();
		// rf.setDlToken();
	}

	
	@Override
	@Cacheable(value = "emToken", key = "#username+'_'+#password")
	public UserToken getToken(String username, String password) {
		UserToken userToken = tokenService.getToken(username, password);
		return userToken;
	}


	/**
	 * 获取token，并将token存入数据库
	 */
	@Override
	public void setDlToken() {
		UserToken userToken = getToken("DL");
		String url = userToken.getGetTokenUrl();
		logger.info(JSONObject.fromObject(userToken).toString());
		String client_id = userToken.getClientId();
		String client_secret = userToken.getClientSecret();
		String timestamp = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
		String password = HttpClientUtil.stringMD5(userToken.getPassword());
		String username = userToken.getUsername();
		Map<String, String> map = new HashMap<String, String>();
		String sign = username + password + client_secret
				+ timestamp.replace(" ", "");
		logger.info("加密前：" + sign);
		sign = HttpClientUtil.stringMD5(sign);
		logger.info("加密后：" + sign);
		map.put("UserId", username);
		map.put("Password", password);
		map.put("RequestTime", timestamp);
		map.put("AuthSign", sign);
		logger.info(JSONObject.fromObject(map).toString());
		String result = HttpClientUtil.httpPost(url, JSONObject.fromObject(map)
				.toString());
		System.out.println("获取token结果：" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		String success = (String) jsonObject.get("StatusCode");
		String token = null;
		if (success.equals("1")) {
			Map resultMap = new HashMap();
			resultMap.put("access_token", (String) jsonObject.get("Token"));
			resultMap.put("refresh_token", "");
			resultMap.put("time", jsonObject.getLong("CurrTime"));
			resultMap.put("expires_in", jsonObject.getInt("Expire"));
			resultMap.put("refresh_token_expires", jsonObject.getLong("Expire"));
			resultMap.put("ecommerce_name", "DL");
			tokenService.updateToken(resultMap);
		} else if (success.equals("2")) {
			logger.info("用户或密码不正确。");
		} else if (success.equals("3")) {
			logger.info("认证签名错误。");
		} else if (success.equals("4")) {
			logger.info("刷新TOKEN时，原始TOKEN异常。");
		} else if (success.equals("5")) {
			logger.info("服务器异常。");
		}

	}

	// 刷新得力token
	@Scheduled(cron = "0 0 0 * * ?")
	@Override
	public void refreshDlToken() {
		UserToken userToken = getToken("DL");
		String refreshToken = userToken.getRefreshToken();
		String refreshTokenUrl = userToken.getRefreshTokenUrl();
		String originaToken = userToken.getAccessToken();
		String userId = userToken.getUsername();
		String password = HttpClientUtil.stringMD5(userToken.getPassword());
		logger.info("得力密码加密前:"+userToken.getPassword()+"加密后"+password);
		Map<String, String> map = new HashMap<String, String>();
		map.put("OriginaToken", originaToken);
		map.put("UserId", userId);
		map.put("Password", password);
		String result = HttpClientUtil.httpPost(refreshTokenUrl, JSONObject
				.fromObject(map).toString());
		JSONObject jsonObject = JSONObject.fromObject(result);
		String success = (String) jsonObject.get("StatusCode");
		String token = null;
		if (success.equals("1")) {
			Map resultMap = new HashMap();
			resultMap.put("access_token", (String) jsonObject.get("Token"));
			resultMap.put("refresh_token", "");
			resultMap.put("time", jsonObject.getLong("CurrTime"));
			resultMap.put("expires_in", jsonObject.getInt("Expire"));
			resultMap
					.put("refresh_token_expires", jsonObject.getLong("Expire"));
			resultMap.put("ecommerce_name", "DL");
			tokenService.updateToken(resultMap);
		}else{
			setDlToken();
		}
	}
	
	
	/**
	 * 获取token，并将token存入数据库
	 */
	@CacheEvict(value = "emToken",allEntries=true ) /**清除缓存*/
	@Override
	public void setXyToken() {
		String token = "";
		UserToken userToken = getToken("XY");
		String url = userToken.getGetTokenUrl();
		String salt = userToken.getRefreshTokenUrl();
		logger.info(JSONObject.fromObject(userToken).toString());
		String cust_id = userToken.getClientId();
		String cust_secret = userToken.getClientSecret();
		StringBuffer sp = new StringBuffer();
		sp.append(url);
		sp.append("?cust_id="+cust_id);
		sp.append("&salt="+salt);
//		JSONObject mustdata = new JSONObject();
//		mustdata.put("subCompUserId", ecommerceUserName);
		String mustdata = "{'subCompUserId':'wengyu2249@163.com'}";
		String signature="cust_id="+cust_id+"&cust_secret="+cust_secret+"&salt="+salt+"&data="+URLEncoder.encode(mustdata);
		signature = HttpClientUtil.stringSHA1(signature);
		sp.append("&signature="+signature);
		sp.append("&data="+URLEncoder.encode(mustdata));
		//URLEncoder.encode(mustdata)
		String urlMap = sp.toString();
		logger.info("获取token参数"+urlMap);
		logger.info("获取西域token"+HttpClientUtil.httpGet(urlMap));
		String result = HttpClientUtil.httpGet(urlMap);
		System.out.println("获取西域token结果：" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		int status =(Integer) jsonObject.get("status");
		if (status==0) {
			logger.info((String) jsonObject.get("message"));
			JSONObject data =(JSONObject) jsonObject.get("data");
		Map <String,String>  resultMap = new HashMap<String,String>();
		resultMap.put("access_token", (String)data.get("token"));
		resultMap.put("refresh_token", "");
		resultMap.put("ecommerce_name", "XY");
		tokenService.updateToken(resultMap);
		token =(String) jsonObject.get("token");
		updateToken("XY");
		} else {
			logger.info("登录失败！");
		}	
		
	}

	// 刷新西域token
//	@Scheduled(cron = "0 0 0 * * ?")
//	@Override
//	public void refreshXyToken() {
//		UserToken userToken = getToken("XY");
//		String refreshToken = userToken.getRefreshToken();
//		String refreshTokenUrl = userToken.getRefreshTokenUrl();
//		String client_id = userToken.getClientId();
//		String client_secret = userToken.getClientSecret();
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("grant_type","password");
//		map.put("refresh_token", refreshToken);
//		map.put("client_id", client_id);
//		map.put("client_secret", client_secret);
//		String result = HttpClientUtil.httpPost(refreshTokenUrl,map);
//		JSONObject jsonObject = JSONObject.fromObject(result);
//		String success = (String) jsonObject.get("StatusCode");
//		String token = null;
//		if (success.equals("1")) {
//			Map resultMap = new HashMap();
//			resultMap.put("access_token", (String) jsonObject.get("Token"));
//			resultMap.put("refresh_token", "");
//			resultMap.put("time", jsonObject.getLong("CurrTime"));
//			resultMap.put("expires_in", jsonObject.getInt("Expire"));
//			resultMap
//					.put("refresh_token_expires", jsonObject.getLong("Expire"));
//			resultMap.put("ecommerce_name", "DL");
//			tokenService.updateToken(resultMap);
//		}else{
//			setXyToken();
//		}
//	}
	
	@CachePut(value = "emToken", key = "#ename")
	public UserToken refreshToken(String ename){
		if("JD".equals(ename)){
			UserToken userToken = getToken(ename);
			String refreshToken = userToken.getRefreshToken();
			String refreshTokenUrl = userToken.getRefreshTokenUrl();
			String clientSecret = userToken.getClientSecret();
			String clientId = userToken.getClientId();
			Map<String, String> map = new HashMap<String, String>();
			map.put("client_id", clientId);
			map.put("client_secret", clientSecret);
			map.put("refresh_token", refreshToken);
			String result = HttpClientUtil.httpPost(refreshTokenUrl, map);
			JSONObject jsonObject = JSONObject.fromObject(result);
			boolean success = (Boolean) jsonObject.get("success");
			if (success) {
				Map resultMap = (Map) jsonObject.get("result");
				resultMap.put("ecommerce_name", "JD");
				tokenService.updateToken(resultMap);
				updateToken("JD");
			} else {
				setJdToken();
			}			
		}else if("DL".equals(ename)){
			UserToken userToken = getToken("DL");
			String refreshToken = userToken.getRefreshToken();
			String refreshTokenUrl = userToken.getRefreshTokenUrl();
			String originaToken = userToken.getAccessToken();
			String userId = userToken.getUsername();
			String password = HttpClientUtil.stringMD5(userToken.getPassword());
			logger.info("得力密码加密前:"+userToken.getPassword()+"加密后"+password);
			Map<String, String> map = new HashMap<String, String>();
			map.put("OriginaToken", originaToken);
			map.put("UserId", userId);
			map.put("Password", password);
			
			String result = HttpClientUtil.httpPost(refreshTokenUrl, JSONObject
					.fromObject(map).toString());
			JSONObject jsonObject = JSONObject.fromObject(result);
			String success = (String) jsonObject.get("StatusCode");
			String token = null;
			if (success.equals("1")) {
				Map resultMap = new HashMap();
				resultMap.put("access_token", (String) jsonObject.get("Token"));
				resultMap.put("refresh_token", "");
				resultMap.put("time", jsonObject.getLong("CurrTime"));
				resultMap.put("expires_in", jsonObject.getInt("Expire"));
				resultMap
						.put("refresh_token_expires", jsonObject.getLong("Expire"));
				resultMap.put("ecommerce_name", "DL");
				tokenService.updateToken(resultMap);
			}else{
				setDlToken();
			}
		}
		UserToken userToken = tokenService.getTokenByName(ename);
		return userToken;
	}

}